var wineApp = wineApp || {};
wineApp.home = (function() {
    var initSearchPage = function() {

        var key = wineApp.tool.getKey("search");
        var searchHistory = null;
        var searchHistory = wineApp.localStorage.get(key);
        if ($.isEmptyObject(searchHistory)) {
            wineApp.localStorage.set(key, []);
            searchHistory = [];
        };
        var liArray = [];
        $.each(searchHistory, function(index, value) {
            var href = value.search_page + "_list.html?key=" + value.key_word;
            var li = '<dl><dd><a href="' + href + '">' + value.key_word + '</a></dd></dl>';
            liArray.push(li);
        });
        $('.wine_search_list').append(liArray.join(''));
        //$('[data-role="listview"]').listview('refresh');
        //bind Event
        $(document).on('click', '#find', onSearch);

    }

    var initPage = function() {
        initEvent();
        //获取广告
        //initAd();
        wineApp.common.initBanner();
        //获取明星产品
        initRecommand();
        //酒庄信息
        initHomeJz();
        //
        checkVersion();

    }

    var checkVersion = function() {
        var verInConfFile = wineApp.CONFIG.VERSION;
        //每次访问时，把app的版本写入内部存储，在和服务器的版本匹配，确认需要不需要下载
        wineApp.localStorage.set('wineApp.version', verInConfFile);
        var verInLocal = wineApp.localStorage.get('wineApp.version');
        var appType = wineApp.ENV.platform === "ios" ? "iphone" : "android";
        var ajaxUrl = wineApp.CONFIG.API.version;
        wineApp.ajax.post(ajaxUrl, {}).done(function(data) {
            var platform = _.find(data.list, function(o) {
                return o.app_type == appType;
            });
            if (!_.isNil(platform) && !_.isNil(platform.download_url) && platform.version != verInLocal) {
                var intRemoteVer = wineApp.tool.convertVertoInt(platform.version);
                var intLocalVer = wineApp.tool.convertVertoInt(verInLocal);
                if (intRemoteVer > intLocalVer) {
                    var url = platform.download_url;
                    layer.open({
                        content: '发现新版本',
                        btn: ['更新', '取消'],
                        yes: function(index) {
                            window.open(url, 'upgrade');
                            wineApp.localStorage.set('wineApp.version', platform.version);
                            layer.close(index);
                        },
                    });
                }
            }
        })
    }

    var initEvent = function() {
        $(document).on('click', '#recommand', function(e) {
            e.preventDefault();
            $('#mkuan').show();
        })
    }

    var initRecommand = function() {
        var ajaxUrl = wineApp.CONFIG.API.homeproducts;
        wineApp.ajax.post(ajaxUrl, {
            name: 'products'
        }).done(buildRecomandData);
    }
    var buildRecomandData = function(data) {
        var template =
            '<dl>' +
            '<dt><a href="app/wine_detail.html?wineId=#id#"><img src="#tuijianImg#"/></a></dt>' +
            '<dd>' +
            '<ul>' +
            '<li><a class="entry_title" href="hj.html?id=#id#">#planName#</a></li>' +
            '<li><b>￥#price#</b><span>￥#oprice#</span></li>' +
            '</ul>' +
            '</dd>' +
            '</dl>';
        var resourceURL = wineApp.tool.getResourceURL();
        var width = wineApp.tool.getScreenWidth();
        console.log(data);
        $.each(data.list, function(index, val) {
            //只显示3个
            if (index === 6) return false;
            var param = {};
            param.tuijianImg = val.titleimg;
            param.id = val.id;
            param.planName = val.title;
            param.oprice = val.oprice;
            param.price = val.price;
            var tmp = template;
            for (var prop in param) {
                var reg = new RegExp("#" + prop + "#", "gm");
                tmp = tmp.replace(reg, param[prop]);
            }

            $('.wine_products').append(tmp);
        });
    }

    var initAd = function() {
        console.log('initAd')
        var ajaxUrl = wineApp.CONFIG.API.banner;
        var doSuccess = function(data) {
            var resourceURL = wineApp.tool.getResourceURL();
            wineApp.common.buildCarousel('#owl-demo', data.banners, function(val) {
                var content = '<a href="#">' +
                    '<img class="scale" src="' + resourceURL + '/' + val.obid + '.' + val.ext + '" width=100%/>' +
                    '</a>'
                return content
            });
            //$('img.scale').imageScale();
        }
        var doFail = function() {

        }
        wineApp.ajax.post(ajaxUrl, {
            name: 'banner'
        }).done(doSuccess);
    }

    var initHomeJz = function() {
        var ajaxUrl = wineApp.CONFIG.API.homejz;
        var doSuccess = function(data) {
            var resourceURL = wineApp.tool.getResourceURL();
            var width = (wineApp.tool.getScreenWidth() * 0.46).toFixed(0);
            var template = $('<ul>');


            $.each(data.list, function(index, val) {
                template.append('<li>' +
                    '<a href="app/jz_detail.html?jzid=' + val.id + '">' +
                    '<img src="' + val.titleimg + '" width=' + width + 'px height=' + width + 'px />' +
                    '<div class="wine_jzabout">' +
                    '<p class="entry_title">' + val.title + '</p>' +
                    '</div>' +
                    '</a></li>')
            });
            $('.wine_jz').append(template);
        }

        wineApp.ajax.post(ajaxUrl, {
            name: 'imgnews'
        }).done(doSuccess);
    }
    var initDRSection = function() {
        var offset = 0;
        var ajaxUrl = wineApp.CONFIG.API.hotSell + '?offset=' + offset + '&fetchSize=5';
        var doSuccess = function(data) {
            buildRecomandData(data);
        }
        var doFail = function() {

        }
        wineApp.ajax.get(ajaxUrl, doSuccess, doFail);
    }

    var onSearch = function() {
        var searchType = $('#searchType').val();
        var keyword = $('#search').val();
        var href = "";
        var isRoot = wineApp.common.isRootPath();
        var path = isRoot ? "app/" : "";
        var key = wineApp.tool.getKey("search");
        if (searchType == 1) {
            //达人
            wineApp.localStorage.set(key, [{
                search_page: "daren",
                key_word: keyword
            }])
            window.location.href = path + "daren_list.html?key=" + keyword;
            //window.localStorage.set()
        } else if (searchType == 2) {
            //酒庄
        } else if (searchType == 3) {
            //红酒
            wineApp.localStorage.set(key, [{
                search_page: "wine",
                key_word: keyword
            }])
            window.location.href = path + "wine_list.html?key=" + keyword;
        }

    }

    return {
        initSearchPage: initSearchPage,
        initDRSection: initDRSection,
        initHomeJz: initHomeJz,
        buildRecomandData: buildRecomandData,
        initAd: initAd,
        initPage: initPage,
        onSearch: onSearch
    }
})();